package com.agileai.crm.module.mytasks.handler;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import com.agileai.common.KeyGenerator;
import com.agileai.crm.cxmodule.ColdCallsManage;
import com.agileai.crm.cxmodule.TaskCycle8ContentManage;
import com.agileai.domain.DataParam;
import com.agileai.domain.DataRow;
import com.agileai.hotweb.bizmoduler.core.TreeAndContentManage;
import com.agileai.hotweb.controller.core.TreeAndContentManageListHandler;
import com.agileai.hotweb.domain.TreeBuilder;
import com.agileai.hotweb.domain.TreeModel;
import com.agileai.hotweb.domain.core.User;
import com.agileai.hotweb.renders.LocalRenderer;
import com.agileai.hotweb.renders.ViewRenderer;
import com.agileai.util.DateUtil;

public class TaskCycle8ContentManageListHandler
        extends TreeAndContentManageListHandler {
	protected HashMap<String, String> tabIdMapping = new HashMap<String,String>();
    public TaskCycle8ContentManageListHandler() {
        super();
        this.serviceId = buildServiceId(TaskCycle8ContentManage.class);
        this.rootColumnId = "00000000-0000-0000-00000000000000000";
        this.defaultTabId = "ColdCalls";
        this.columnIdField = "TASK_REVIEW_ID";
        this.columnNameField = "TC_PERIOD";
        this.columnParentIdField = "TC_FID";
        this.columnSortField = "TC_PERIOD";
    }
    
	public ViewRenderer prepareDisplay(DataParam param){
		initParameters(param);
		this.setAttributes(param);
		String columnId = param.get("columnId",this.rootColumnId);
		this.setAttribute("columnId", columnId);
		this.setAttribute("isRootColumnId",String.valueOf(this.rootColumnId.equals(columnId)));
		
		TreeBuilder treeBuilder = provideTreeBuilder(param);
		TreeModel treeModel = treeBuilder.buildTreeModel();
		
		String menuTreeSyntax = this.getTreeSyntax(treeModel,new StringBuffer());
		this.setAttribute("menuTreeSyntax", menuTreeSyntax);
		String tabId = param.get(TreeAndContentManage.TAB_ID,this.defaultTabId);

		String currentSubTableId = param.get("currentSubTableId", defaultTabId);
		this.setAttribute("currentSubTableId", currentSubTableId);
		this.setAttribute("currentSubTableIndex",getTabIndex(currentSubTableId));
		
		tabIdMapping.put("ColdCalls", "Layer0");
		tabIdMapping.put("FollowUp", "Layer1");
		tabIdMapping.put("WorkSummary", "Layer2");
		
		setAttribute("currentLayerleId", tabIdMapping.get(currentSubTableId));
		
		this.setAttribute(TreeAndContentManage.TAB_ID, tabId);
		this.setAttribute(TreeAndContentManage.TAB_INDEX, getTabIndex(tabId));
		
		processPageAttributes(param);
		
		DataRow dataRow = getService().getSummaryRecord(new DataParam("TASK_REVIEW_ID", columnId));
		if(dataRow != null && !dataRow.isEmpty()){
			String reviewState = dataRow.getString("TASK_REVIEW_STATE");
			if("Init".endsWith(reviewState)){
				this.setAttribute("doDel",true);
			}
			if("Init".endsWith(reviewState)||"SubmitPlan".endsWith(reviewState) ||"ConfirmPlan".endsWith(reviewState)){
				this.setAttribute("thirdTabName","计划概览");
			}else if("SubmitSummary".endsWith(reviewState)||"ConfirmSummary".endsWith(reviewState)){
				this.setAttribute("thirdTabName","工作总结");
			}
		}else{
			this.setAttribute("thirdTabName","没有计划");
		}
		return new LocalRenderer(getPage());
	}
    
	public ViewRenderer doChangeSubTableAction(DataParam param) {
		return prepareDisplay(param);
	}

    protected void processPageAttributes(DataParam param) {
        String tabId = param.get(TreeAndContentManage.TAB_ID, this.defaultTabId);

        if ("TaskReview".equals(tabId)) {
        }
    	this.setAttribute("currentSubTableId", param.get("currentSubTableId"));
    	setAttribute("currentSubTableId",getAttributeValue("currentSubTableId", "0"));
    }

    protected void initParameters(DataParam param) {
        String tabId = param.get(TreeAndContentManage.TAB_ID, this.defaultTabId);

        if ("TaskReview".equals(tabId)) {
        }
        
        
        
    }

    protected TreeBuilder provideTreeBuilder(DataParam param) {
        TaskCycle8ContentManage service = this.getService();
		User user = (User) getUser();
		String saleId = user.getUserId();
        DataParam saleParam = new DataParam("SALE_ID",saleId);
        List<DataRow> menuRecords = service.findTreeRecords(saleParam);
        TreeBuilder treeBuilder = new TreeBuilder(menuRecords,
                                                  this.columnIdField,
                                                  this.columnNameField,
                                                  this.columnParentIdField);

        return treeBuilder;
    }

    protected List<String> getTabList() {
        List<String> result = new ArrayList<String>();
        result.add("TaskReview");

        return result;
    }
    
	public ViewRenderer doGeneratPlanAction(DataParam param) {
		User user = (User) getUser();
		String saleId = user.getUserId();
		param.put("SALE_ID", saleId);
		param.put("TASK_REVIEW_STATE", "Init");
		param.put("TASK_REVIEW_DESC", "<ol><li>完成情况</li><ul><li>情况1</li><li>情况2</li></ul><li>未完成原因</li><ul><li>原因1</li><li>原因2</li></ul></ol>");
		getService().generatPlanRecord(param);
		extractPlannedVisitTask(param);
		extractUnfinishedTask(param);
		return prepareDisplay(param);
	}
	
	public void extractUnfinishedTask(DataParam param) {
		List<DataRow> rsList = getService().queryPeriodicTreeRecords(param);
		if(rsList.size() > 1){
			String taskReviewId = rsList.get(1).getString("TASK_REVIEW_ID");
			List<DataRow> UnfinishedList = getService().queryUnfinishedTaskRecords(new DataParam("TASK_REVIEW_ID",taskReviewId));
			String dateStr = DateUtil.getDateByType(DateUtil.YYMMDDHHMISS_HORIZONTAL, new Date());
	    	for(int i=0;i < UnfinishedList.size();i++){
	    		DataRow dataRow = UnfinishedList.get(i);
	    		String orgId = dataRow.getString("ORG_ID");
	    		DataParam myTasksParam = new DataParam();
	    		myTasksParam.put("TASK_ID", KeyGenerator.instance().genKey());
	    		myTasksParam.put("ORG_ID", orgId);
	    		myTasksParam.put("CUST_ID", dataRow.get("CUST_ID"));
	    		myTasksParam.put("TASK_REVIEW_ID", param.get("TASK_REVIEW_ID"));
	    		myTasksParam.put("SALE_ID", dataRow.get("ORG_SALESMAN"));
	    		myTasksParam.put("TASK_FOLLOW_STATE", "NoFollowUp");
	    		myTasksParam.put("TASK_CLASS", dataRow.getString("TASK_CLASS"));
	    		myTasksParam.put("TASK_CREATE_TIME", dateStr);
	    		myTasksParam.put("TASK_FINISH_TIME", "");
	    		myTasksParam.put("TASK_CUST_STATE", "");
	    		ColdCallsManage coldCallsManage = this.lookupService(ColdCallsManage.class);
	    		coldCallsManage.createMasterRecord(myTasksParam);
	    	}
		}
	}
	
	public void extractPlannedVisitTask(DataParam param) {
		DataRow dateRow = getService().queryTreeRecord(param);
		DataParam visitAgainParam = new DataParam();
		visitAgainParam.put("stime", dateRow.get("TC_BEGIN"));
		visitAgainParam.put("etime", dateRow.get("TC_END"));
		visitAgainParam.put("ORG_SALESMAN", param.get("SALE_ID"));
		List<DataRow> proList = getService().findProPlanVisitRecords(visitAgainParam);
		String dateStr = DateUtil.getDateByType(DateUtil.YYMMDDHHMISS_HORIZONTAL, new Date());
    	for(int i=0;i < proList.size();i++){
    		DataRow dataRow = proList.get(i);
    		String orgId = dataRow.getString("ORG_ID");
    		DataParam myTasksParam = new DataParam();
    		myTasksParam.put("TASK_ID", KeyGenerator.instance().genKey());
    		myTasksParam.put("ORG_ID", orgId);
    		myTasksParam.put("CUST_ID", dataRow.get("CUST_ID"));
    		myTasksParam.put("TASK_REVIEW_ID", param.get("TASK_REVIEW_ID"));
    		myTasksParam.put("SALE_ID", dataRow.get("ORG_SALESMAN"));
    		myTasksParam.put("TASK_FOLLOW_STATE", "NoFollowUp");
    		myTasksParam.put("TASK_CLASS", "ColdCalls");
    		myTasksParam.put("TASK_CREATE_TIME", dateStr);
    		myTasksParam.put("TASK_FINISH_TIME", "");
    		myTasksParam.put("TASK_CUST_STATE", "");
    		ColdCallsManage coldCallsManage = this.lookupService(ColdCallsManage.class);
    		coldCallsManage.createMasterRecord(myTasksParam);
    	}
    	
    	User user = (User) getUser();
    	String userId = user.getUserId();
    	visitAgainParam.put("SALE_ID", param.get("SALE_ID"));
		List<DataRow> custList = getService().findCustPlanVisitRecords(visitAgainParam);
    	for(int i=0;i < custList.size();i++){
    		DataRow dataRow = custList.get(i);
    		String custId = dataRow.getString("CUST_ID");
    		DataParam myTasksParam = new DataParam();
    		myTasksParam.put("TASK_ID", KeyGenerator.instance().genKey());
    		myTasksParam.put("ORG_ID", dataRow.get("ORG_ID"));
    		myTasksParam.put("CUST_ID", custId);
    		myTasksParam.put("TASK_REVIEW_ID", param.get("TASK_REVIEW_ID"));
    		myTasksParam.put("SALE_ID", userId);
    		myTasksParam.put("TASK_FOLLOW_STATE", "NoFollowUp");
    		myTasksParam.put("TASK_CLASS", "FollowUp");
    		myTasksParam.put("TASK_CREATE_TIME", dateStr);
    		myTasksParam.put("TASK_FINISH_TIME", "");
    		myTasksParam.put("TASK_CUST_STATE", "");
    		ColdCallsManage coldCallsManage = this.lookupService(ColdCallsManage.class);
    		coldCallsManage.createMasterRecord(myTasksParam);
    	}
	}
	
	public ViewRenderer doDelPlanAction(DataParam param) {
		String columnId = param.get("columnId");
		DataRow dataRow = getService().getSummaryRecord(new DataParam("TASK_REVIEW_ID", columnId));
		if(dataRow != null && !dataRow.isEmpty()){
			String reviewState = dataRow.getString("TASK_REVIEW_STATE");
			if(!"Init".endsWith(reviewState)){
				setErrorMsg("任务计划状态不是初始化的记录不能删除！！！");
			}else{
				getService().deleteTaskReviewRecord(columnId);
			}
		}
		param.put("columnId", rootColumnId);
		return prepareDisplay(param);
	}

    protected TaskCycle8ContentManage getService() {
        return (TaskCycle8ContentManage) this.lookupService(this.getServiceId());
    }
}

